package org.example.utils;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;

import java.io.IOException;
import java.lang.reflect.Field;

public class SolrUtil<T> {
    private static final String SOLR_URL = "http://localhost:8983/solr/";
    private static final String CORE_NAME = "itripHotel";
    private static HttpSolrClient client = null;

    /**
     * create solr request
     * @return HttpSolrClient
     */
    public static HttpSolrClient createSolrHttpRequest(){
        client = new HttpSolrClient.Builder(SOLR_URL+CORE_NAME).withConnectionTimeout(10000).build();
        return client;
    }

    /**
     * get SolrQuery
     * @param entity entity Class
     * @param params type
     * @param <T> entity Type
     * @return query
     */
    public static <T> SolrQuery getSolrQuery(Class<T> entity, String params){
        Field[] fields = entity.getDeclaredFields();//gets all entity of fields
        SolrQuery query = new SolrQuery(params);//instantiation SolrQuery
        String [] filedNames = new String[fields.length];//used to fields names
        for (int i = 0; i < fields.length; i++) {filedNames[i] = fields[i].getName(); }//assignment
        query.setFields(filedNames);//bind all fieldsNames
        return query;
    }

    /**
     * get solr documentList
     * @param query SolrQuery
     * @return SolrDocumentList
     */
    public static SolrDocumentList getSolrDocumentList(SolrQuery query){
        try {
            QueryResponse response = SolrUtil.createSolrHttpRequest().query(query);//pass in query with a condition
            return response.getResults();
        } catch (SolrServerException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * close solr request
     * close HttpSolrClient
     */
    public static void closeClient(){
        if (client!=null){
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
